package com.stars.home.vmodel

import android.app.Activity
import android.app.Application
import android.view.View
import androidx.databinding.Bindable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hwangjr.rxbus.RxBus
import com.stars.home.BR
import com.stars.home.R
import com.stars.home.activity.ForgetPasswordActivity
import com.stars.home.activity.MainActivity
import com.stars.home.config.ConfigMMKV
import com.stars.home.config.ConfigRx
import com.stars.home.model.LoginBean
import com.stars.home.utils.net.NetEngine
import com.tencent.mmkv.MMKV
import com.trailer.base.base.BRepository
import com.trailer.base.base.BViewModel
import com.trailer.base.utils.B
import com.trailer.base.utils.MMKVManager
import com.trailer.base.utils.UiSwitch
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit


open class LoginVModel(application: Application) : BViewModel<BRepository>(application) {


    var one= MutableLiveData<Boolean>(true)

    var adminType="main"//driver是司机 main是货主

    var code:String?=""

    var codeTip: MutableLiveData<String> = MutableLiveData(RegisterVModel.getCodeStr)
    private var disposable: Disposable? = null


    //切换登录方式
    var switchType = MutableLiveData<String>()
    var passwordVisiblity = MutableLiveData<Int>()
    var codeVisibility = MutableLiveData<Int>()
    private var showType = true


    companion object {
        const val time = 60
        var timeStart: Long = 1
        const val getCodeStr = "获取验证码"

    }

    init {
        passwordVisiblity.value = View.GONE
        codeVisibility.value = View.VISIBLE
        switchType.value = "使用密码登录"


    }

    fun setShowType() {

        if (showType) {//验证码显示-密码显示
            passwordVisiblity.value = View.VISIBLE
            codeVisibility.value = View.GONE
            switchType.value = "使用验证码登录"

        } else {//密码显示-验证码
            passwordVisiblity.value = View.GONE
            codeVisibility.value = View.VISIBLE
            switchType.value = "使用密码登录"
        }
        showType = !showType
    }


    @Bindable
    open var phone: String? =null
        set(value) {
            field = value
            notifyPropertyChanged(BR.phone)
        }


    @Bindable
    open var passWord: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.passWord)
        }

    @Bindable
    open var passWordTo: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.passWordTo)
        }


    fun toChose(type: Int){

        if(type==1){
            one.value=true
            adminType="main"
        }else{
            one.value=false
            adminType="driver"
        }

    }


    fun loginTo(){
        if (showType) {//验证码登录

            smsLogin()

        } else {//密码登录
            login()

        }
    }


    fun smsLogin(){

        if (phone.isNullOrEmpty()) {
            toast(R.string.please_input_user_phone)
            return
        }
        if (passWordTo.isNullOrEmpty()) {
            toast("请输入手机验证码")
            return
        }

        viewModelScope.launch {
            val it = repository().lreq { NetEngine.service.mobilelogin(phone, passWordTo, adminType,code) }
            if (it.ok(true)) {

                var bean: LoginBean =it.data() as LoginBean
                MMKV.defaultMMKV().putString("token", bean.token)
                UiSwitch.single(repository().context, MainActivity::class.java)

                RxBus.get().post(ConfigRx.CLOSE_LOGIN, "")
                (repository().context as Activity).finish()
            }
        }

    }


    fun login() {

        if (phone.isNullOrEmpty()) {
            toast(R.string.please_input_user_phone)
            return
        }
        if (passWord.isNullOrEmpty()) {
            toast(R.string.please_input_pwd)
            return
        }

        viewModelScope.launch {
            val it = repository().lreq { NetEngine.service.login(phone, passWord, adminType,code) }
            if (it.ok(true)) {

                var bean: LoginBean =it.data() as LoginBean
                MMKV.defaultMMKV().putString("token", bean.token)
                UiSwitch.single(repository().context, MainActivity::class.java)

                RxBus.get().post(ConfigRx.CLOSE_LOGIN, "")
                (repository().context as Activity).finish()
            }
        }


    }


    fun goRetrieveWord(){

        UiSwitch.bundle(repository().context as Activity, ForgetPasswordActivity::class.java,
                B().putString("adminType",adminType).ok())

    }


    fun getSmsCode(start: Long = 1) {
        if (codeTip.value != ForgetPasswordVModel.getCodeStr) {
            return
        }

        if (phone.isNullOrEmpty()) {
            toast(R.string.please_input_user_phone)
            return
        }

        viewModelScope.launch {

            val it = repository().lreq { NetEngine.service.getPassword(phone,"login",adminType) }
            if (it.ok(true)) {
                startTimer(start)
            }

        }

    }

    private fun startTimer(start: Long = 1) {
        disposeTimer()
        disposable = Observable.intervalRange(start, ForgetPasswordVModel.time - start + 1, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext {
                    ForgetPasswordVModel.timeStart = it
                    codeTip.value = if (ForgetPasswordVModel.time - it > 0) "${ForgetPasswordVModel.time - it}秒后重发" else {
                        ForgetPasswordVModel.getCodeStr
                    }
                }
                .doOnComplete() {
                    MMKVManager.instance().encode(ConfigMMKV.REGISTER_TIME_START, 60)
                }
                .doOnDispose() {
                    MMKVManager.instance().encode(ConfigMMKV.REGISTER_TIME_START, 60)
                }
                .subscribe()
    }

    private fun disposeTimer() {
        disposable?.isDisposed ?: disposable?.dispose()
    }

}
